import time
import subprocess
import tkinter as tk
from tkinter import messagebox, filedialog
import threading

# 获取进程
def get_processes(program_name):
    """获取所有匹配的进程"""
    try:
        output = subprocess.check_output(['tasklist']).decode('gbk')
        return [line.split()[1] for line in output.strip().split('\n') if program_name in line]
    except subprocess.CalledProcessError as e:
        print(f"获取进程时出错: {e}")
        return []
    except UnicodeDecodeError as e:
        print(f"解码错误: {e}")
        return []

# 关闭程序
def close_program(process_ids):
    """关闭指定的程序"""
    for pid in process_ids:
        if messagebox.askyesno("确认", f"您确认要关闭进程 {pid} 吗？"):
            try:
                subprocess.check_call(['taskkill', '/F', '/PID', pid])
                print(f"进程 {pid} 已关闭")
            except subprocess.CalledProcessError as e:
                print(f"关闭进程 {pid} 时出错: {e}")

# 监控线程
def monitor(program_path, total_seconds):
    program_name = program_path.split('\\')[-1]
    status_label.config(text="监控中...")
    start_time = time.time()

    while not stop_monitoring.is_set():
        current_time = time.time()
        elapsed_time = current_time - start_time

        # 检查时间条件
        if (elapsed_time >= total_seconds):
            process_ids = get_processes(program_name)
            if process_ids:
                print(f"时间到，找到以下匹配的进程: {process_ids}")
                close_program(process_ids)
            # 重置开始时间以继续监控
            start_time = current_time

        # 更新时间标签
        remaining_time = total_seconds - (elapsed_time % total_seconds)
        countdown_label.config(text=f"下次关闭倒计时: {int(remaining_time)} 秒")
        time.sleep(1)

    status_label.config(text="监控停止.")

# 启动监控的回调
def on_start():
    program_path = program_path_var.get()
    if not program_path:
        messagebox.showwarning("警告", "请选择要关闭的程序路径")
        return

    try:
        total_seconds = sum([
            int(day_var.get()) * 86400,
            int(hour_var.get()) * 3600,
            int(minute_var.get()) * 60,
            int(second_var.get())
        ])
    except ValueError:
        messagebox.showwarning("警告", "时间输入无效")
        return

    if total_seconds <= 0:
        messagebox.showwarning("警告", "请设置一个有效的时间间隔")
        return

    stop_monitoring.clear()
    monitoring_thread = threading.Thread(target=monitor, args=(program_path, total_seconds))
    monitoring_thread.daemon = True
    monitoring_thread.start()

# 停止监控的回调
def on_stop():
    stop_monitoring.set()

# 选择程序路径的回调
def select_program():
    file_path = filedialog.askopenfilename(title="选择要关闭的程序", filetypes=[("Executable Files", "*.exe")])
    if file_path:
        program_path_var.set(file_path)

# 创建GUI界面
root = tk.Tk()
root.title("程序定时关闭器")
stop_monitoring = threading.Event()

# 程序路径选择部分
program_path_var = tk.StringVar()
tk.Label(root, text="程序路径:").pack()
program_button = tk.Button(root, text="选择程序", command=select_program)
program_button.pack()
program_path_entry = tk.Entry(root, textvariable=program_path_var, width=50)
program_path_entry.pack()

# 时间选择部分
tk.Label(root, text="选择时间间隔:").pack()

# 天数选择
day_var = tk.IntVar(value=0)
tk.Label(root, text="天数:").pack()
day_scale = tk.Scale(root, from_=0, to=30, orient=tk.HORIZONTAL, variable=day_var)
day_scale.pack()

# 小时选择
hour_var = tk.IntVar(value=0)
tk.Label(root, text="小时:").pack()
hour_scale = tk.Scale(root, from_=0, to=23, orient=tk.HORIZONTAL, variable=hour_var)
hour_scale.pack()

# 分钟选择
minute_var = tk.IntVar(value=0)
tk.Label(root, text="分钟:").pack()
minute_scale = tk.Scale(root, from_=0, to=59, orient=tk.HORIZONTAL, variable=minute_var)
minute_scale.pack()

# 秒钟选择
second_var = tk.IntVar(value=0)
tk.Label(root, text="秒:").pack()
second_scale = tk.Scale(root, from_=0, to=59, orient=tk.HORIZONTAL, variable=second_var)
second_scale.pack()

# 监控模式选择
monitor_type_var = tk.StringVar(value="start_now")
tk.Radiobutton(root, text="从当前时间开始计时", variable=monitor_type_var, value="start_now").pack()
tk.Radiobutton(root, text="从00:00开始计时", variable=monitor_type_var, value="from_midnight").pack()

# 启动监控按钮
start_button = tk.Button(root, text="开始监控", command=on_start)
start_button.pack()

# 停止监控按钮
stop_button = tk.Button(root, text="停止监控", command=on_stop)
stop_button.pack()

# 状态标签
status_label = tk.Label(root, text="", fg="blue")
status_label.pack()

# 倒计时标签
countdown_label = tk.Label(root, text="", fg="red")
countdown_label.pack()

root.mainloop()
